package list;

public class HasCycleTwo {
    public static void main(String[] args) {
        System.out.println(22);
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(3);

        l1.next = l2;
        l2.next = l3;
        // l3.next = l1;

        ListNode ret = hasCycle(l1);
        System.out.println(ret);
    }

    public static ListNode hasCycle(ListNode head) {
        // Set<ListNode> content = new HashSet<>();
        // while (head != null) {
        // if (!content.add(head)) {
        // return head;
        // }

        // head = head.next;
        // }

        // return head;

        if (head == null) {
            return null;
        }

        ListNode fast = head;
        ListNode slow = head;
        while (fast != null) {
            slow = head.next;
            if (fast.next != null) {
                fast = fast.next.next;
            } else {
                return null;
            }

            if (fast == slow) {
                ListNode ptr = head;

                while (ptr != slow) {
                    ptr = ptr.next;
                    slow = slow.next;
                }

                return ptr;
            }
        }

        return null;
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
        next = null;
    }
}